<?php

namespace app\index\controller;

use app\admin\service\OssService;
use app\BaseController;
use app\index\model\PohtoListImage;
use app\index\model\PhotoColl as PhotoCollModal;
use app\index\model\PhotoList as PhotoListModal;
use app\index\model\PohtoInstitution as PohtoInstitutionModal;
use app\index\model\PohtoUser as PohtoUserModal;
use app\index\model\PohtoType as PohtoTypeModal;
use app\index\model\PohtoTag as PohtoTagModal;
use app\index\model\SearchLog as SearchLogModal;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class PhotoPc extends BaseController
{
    public function test()
    {
        $params = $this->request->post(['arr', 'dir', 'video_count']);
        $listSql = new PhotoListModal();
        $info = $listSql->where('name', '=', $params['dir'])->findOrEmpty();
        if ($info->isEmpty()) {
            $listSql->save([
                'author_id' => 14,
                'country' => '中国',
                'extracted_code' => 'xiaobaiquan',
                'jiangkuaihe' => 'xiaobaiquan',
                'name' => $params['dir'],
                'netdisk' => 0,
                'cover' => $params['arr'][0]['image_url'],
                'photo_count' => count($params['arr']),
                'video_count' => $params['video_count'],
                'price' => 0,
                'private' => 0,
                'sort' => 1,
                'type_id' => 13,
                'tags' => [],
                'zipSize' => ''
            ]);
            foreach ($params['arr'] as $k => $item) {
                $params['arr'][$k]['photo_id'] = $listSql->id;
            }
        } else {
            foreach ($params['arr'] as $k => $item) {
                $params['arr'][$k]['photo_id'] = $info->id;
            }
        }
        $sql = new PohtoListImage();
        $sql->saveAll($params['arr']);
        return '1';
    }
    public function getInfo() {
        $sql = new PohtoListImage();
        $info = $sql
            ->where('photo_id', '<>', 107)
            ->where('photo_id', '<>', 109)
            ->where('image_url', 'LIKE','%xiaobaiquan.hfxfd.asia%')
            ->limit(1)->select()->toArray();
        $path = 'E:/album'.$info[0]['image_path'];
//        dump($path);
        $client = new Client([
            'verify' => false,
            'timeout' => 30, // Increase timeout to 30 seconds
        ]);
//        try {
            $response = $client->post('https://www.picgo.net/api/1/upload', [
                'headers' => [
//                    'X-API-Key' => 'chv_JYAw_cf63a2b2c9581894c46c2a7f0a0e3d5f08c2ca1011b0cec2dce723e4f8d1d53763165123fb944e49425fe10510d3e6f00f66f0d52e7114a06e20d9eb57dae696',
                    'X-API-Key' => 'chv_hQVi_33e809a18f6ae1b49c3df6ca2d2624a9236731433f732442a2dcb3c16549af46fc7d576e5fcc580faf8e8ef82301a7b8b32007761d26e310bf9ca6f3a8c8dff0',
                ],
                'multipart' => [
                    [
                        'name' => 'source',
                        'contents' => fopen($path, 'r'),
                    ],
                ],
            ]);
            $responseBody = $response->getBody()->getContents();
            $responseData = json_decode($responseBody, true);
            $imageUrl = $responseData['image']['url'];
            $sql->update([
                'image_url' => $imageUrl
            ], [
                'id' => $info[0]['id']
            ]);
            return 'true';
//        } catch (RequestException $e) {
//            return $path;
//        } catch (\Exception $e) {
//            return $path;
//        }
    }
    public function getInfoTwo() {
        $sql = new PohtoListImage();
        $info = $sql->where('image_url', 'LIKE','%xiaobaiquan.hfxfd.asia%')->limit(1)->select()->toArray();
        $path = 'E:/album'.$info[0]['image_path'];
        $client = new Client([
            'verify' => false,
            'timeout' => 30, // Increase timeout to 30 seconds
        ]);
        try {
            $response = $client->post('https://api.imgbb.com/1/upload', [
                'multipart' => [
                    [
                        'key' => '5589afe3c6c55e2f48178f7474bbe105',
                        'name' => 'source',
                        'image' => fopen($path, 'r'),
                    ],
                ],
            ]);
            $responseBody = $response->getBody()->getContents();
            $responseData = json_decode($responseBody, true);
            $imageUrl = $responseData['image']['url'];
            $sql->update([
                'image_url' => $imageUrl
            ], [
                'id' => $info[0]['id']
            ]);
            return 'true';
        } catch (RequestException $e) {
            return 'false';
        } catch (\Exception $e) {
            return 'false';
        }
    }
    public function horUser()
    {
        $userSql = new PohtoUserModal();
        $list = $userSql->where('hot', '=', '1')->order('sort desc')->with('institutionName')->select();
        if(config('app.imgtype') == 'other') {
            return result()->success($list);

        } else {
            $oss = new OssService();
            return result()->success($oss->signIds($list, 'avatar', 'avatar_show'));
        }
    }

    public function searchList()
    {
        $sql = new SearchLogModal();
        $list = $sql->limit(50)->order('count', 'desc')->select();
        return result()->success($list);
    }

    public function tags()
    {
        $sql = new PohtoTagModal();
        $list = $sql->orderRaw("rand() , id DESC")->limit(50)->select();
        return result()->success($list);
    }
    public function userList() {
        $params = $this->request->post(['current', 'size', 'id', 'username']);
        $sql = new PohtoUserModal();
        $whereArr = [];
        if(isset($params['username']) && $params['username']) {
            $whereArr[] = ["username", "LIKE", '%'.$params['username'].'%'];
        }
        if(isset($params['id']) && $params['id']) {
            $whereArr[] = ["id", "=", $params['id']];
        }
        $list = $sql
            ->where($whereArr)
            ->with(['institutionName'])
            ->order('sort desc')
            ->paginate([
                'list_rows'=> $params['size'],
                'page' => $params['current'],
            ])->toArray();
        if(config('app.imgtype') == 'other') {
            return result()->success($list);
        } else {
            $oss = new OssService();
            return result()->success($oss->signIds($list, 'avatar', 'avatar_show'));

        }
    }

    public function institutionUser()
    {
        $params = $this->request->post(['institution_id']);
        $sql = new PohtoUserModal();
        $list = $sql->where('institution_id', $params['institution_id'])->order('sort desc')->select();
        return result()->success($list);
    }
    public function pcInstitutionList()
    {
        $sql = new PohtoInstitutionModal();
        $list = $sql->order('create_at desc')
            ->select();
        return result()->success($list);
    }
    public function horList()
    {
        $sql = new PhotoListModal();
        $list = $sql
            ->where('hot', '=', '1')->where('status', 'SUCCESS')->with(['tanName', 'userInfo'])->select();
        foreach ($list as $key => $item) {
            $list[$key]['vip_price'] = floor($item['price'] * config('app.vipDis'));
            if(config('app.imgtype') == 'local') {
                $list[$key]['image_url']= $item['image_path'];
            }
        }
        return result()->success($list);
    }
    public function todayList()
    {
        $sql = new PhotoListModal();
        $today = date('Y-m-d');
        $list = $sql->whereRaw("DATE(FROM_UNIXTIME(create_at)) = ?", [$today])->with(['tanName', 'userInfo'])->withCount(['like', 'coll', 'buy'])->select();
        return result()->success($list);
    }
    public function selectedList()
    {
        // 精选列表
        $params = $this->request->post(['current', 'size', 'fee', 'id', 'tags', 'institution_id', 'author_id', 'order', 'orderType']);
        $sql = new PhotoListModal();
        $whereArr[] = ['private', '=', 0];
        $whereArr[] = ['selected', '=', 1];
        if(isset($params['fee']) && $params['fee']) {
            $whereArr[] = ['price', '=', 0];
        } else {
            $whereArr[] = ['price', '<>', 0];
        }
        if(isset($params['id']) && $params['id']) {
            $whereArr[] = ['type_id', '=', $params['id']];
        }
        if(isset($params['author_id']) && $params['author_id']) {
            $whereArr[] = ['author_id', '=', $params['author_id']];
        }
        $condition = isset($params['institution_id']) && $params['institution_id'];
        $haswhereArr = [];
        if($condition) {
            $haswhereArr[] = ['institution_id', '=', $params['institution_id']];
        }
        $whereOr = [];
        if(isset($params['tags']) && $params['tags']) {
            foreach($params['tags'] as $item){
                $whereOr[] = ["tags", "find in set", $item];
            }
        }

        $orderArr = $this->getOrder($params);
        $list = $sql
            ->where(function ($query) use($whereOr) {
                $query->whereOr($whereOr);
            })
            ->where($whereArr)
            ->when($condition, function ($query) use($haswhereArr) {
                $query->where('author_id', 'IN', function ($query) use($haswhereArr) {
                    $query->table('car_photo_user')->where($haswhereArr)->field('id');
                });
            })
            ->with(['tanName', 'userInfo'])
            ->withCount(['like', 'coll', 'buy'])
            ->order($orderArr)
            ->paginate([
                'list_rows'=> $params['size'],
                'page' => $params['current'],
            ]);
        return result()->success($list);
    }

    public function collList()
    {
        $params = $this->request->post(['current', 'size', 'userid', 'work_id', 'type_id', 'author_id', 'institution_id', 'keyword', 'tags']);
        $sql = new PhotoCollModal();
        $whereArr[] = ['userid', '=', $params['userid']];
        if(isset($params['work_id']) && $params['work_id']) {
            $whereArr[] = ["work_id", "=", $params['work_id']];
        }
        $infoWhereArr[] = ['private', '=', 0];
        $whereOr = [];
        if(isset($params['type_id']) && $params['type_id']) {
            $infoWhereArr[] = ["type_id", "=", $params['type_id']];
        }
        if(isset($params['keyword']) && $params['keyword']) {
            $infoWhereArr[] = ["name", "LIKE", '%'.$params['keyword'].'%'];
        }
        if(isset($params['tags']) && $params['tags']) {
            foreach($params['tags'] as $item){
                $whereOr[] = ["tags", "find in set", $item];
            }
        }
        $condition = count($infoWhereArr) + count($whereOr) > 0;
        $list = $sql
            ->where($whereArr)
            ->when($condition, function ($query) use($infoWhereArr) {
                $query->hasWhere('info', $infoWhereArr);
            })
            ->page($params['current'])
            ->limit($params['size'])
            ->with(['info'])
            ->where(function ($query) use($whereOr) {
                $query->whereOr($whereOr);
            })
            ->order('create_at desc')
            ->select();
        $total = $sql
            ->where($whereArr)
            ->when($condition, function ($query) use($infoWhereArr) {
                $query->hasWhere('info', $infoWhereArr);
            })
            ->where(function ($query) use($whereOr) {
                $query->whereOr($whereOr);
            })
            ->count();
        foreach ($list as $key => $value) {
            $info = $value['info'];
            $info['vip_price'] = floor($info['price'] * config('app.vipDis'));
            if(config('app.imgtype') == 'local') {
                $info['image_url']= $info['image_path'];
            }
            $list[$key] = $info;
        }
        return result()->success([
            'data' => $list,
            'total' => $total
        ]);
    }
    public function list()
    {
        $params = $this->request->post(['current', 'keyword', 'size', 'fee', 'id', 'tags', 'institution_id', 'author_id', 'releaseid', 'order', 'orderType']);
        $sql = new PhotoListModal();
        $whereArr[] = ['status', '=', 'SUCCESS'];
        $whereArr[] = ['private', '=', 0];
        if(isset($params['fee'])) {
            if($params['fee']) {
                $whereArr[] = ['price', '=', 0];
            } else {
                $whereArr[] = ['price', '<>', 0];
            }
        }
        if(isset($params['id']) && $params['id']) {
            $whereArr[] = ['type_id', '=', $params['id']];
        }
        if(isset($params['author_id']) && $params['author_id']) {
            $whereArr[] = ['author_id', '=', $params['author_id']];
        }
        if(isset($params['releaseid']) && $params['releaseid']) {
            $whereArr[] = ['releaseid', '=', $params['releaseid']];
        }
        if(isset($params['keyword']) && $params['keyword']) {
            $whereArr[] = ["name", "LIKE", '%'.$params['keyword'].'%'];
            $log = new SearchLogModal();
            $logInfo = $log->where('text', $params['keyword'])->findOrEmpty();
            if($logInfo->isEmpty()) {
                $log->save([
                    'text' => $params['keyword'],
                    'count' => 1
                ]);
            } else {
                $logInfo->count = $logInfo->count + 1;
                $logInfo->save();
            }
        }
        $condition = isset($params['institution_id']) && $params['institution_id'];
        $haswhereArr = [];
        if($condition) {
            $haswhereArr[] = ['institution_id', '=', $params['institution_id']];
        }
        $whereOr = [];
        if(isset($params['tags']) && $params['tags']) {
            foreach($params['tags'] as $item){
                $whereOr[] = ["tags", "find in set", $item];
            }
        }

        $orderArr = $this->getOrder($params);
        $list = $sql
            ->where(function ($query) use($whereOr) {
                $query->whereOr($whereOr);
            })
            ->where($whereArr)
            ->when($condition, function ($query) use($haswhereArr) {
                $query->where('author_id', 'IN', function ($query) use($haswhereArr) {
                    $query->table('car_photo_user')->where($haswhereArr)->field('id');
                });
            })
            ->with(['tanName', 'userInfo', 'imgHeight'])
            ->withCount(['like', 'coll', 'buy'])
            ->order($orderArr)
            ->paginate([
                'list_rows'=> $params['size'],
                'page' => $params['current'],
            ]);
        return result()->success($list);
    }

    public function detailView()
    {
        $params = $this->request->post(['id']);
        $sql = new PhotoListModal();
        $sql->where('id', $params['id'])
            ->inc('view')
            ->update();
        return result()->onlySucMsg("增加成功");
    }
    private function getOrder($params)
    {
        if(isset($params['order']) && $params['order'] && $params['order'] != 'view') {
            if($params['order'] === 'create_at') {
                return [
                    'create_at' => $params['orderType'],
                    'view' => 'desc',
                    'sort' => 'desc',
                ];
            }
            $orderName = $params['order']."_count";
            return [
                $orderName => $params['orderType'],
                'view' => 'desc',
                'sort' => 'desc',
                'create_at' => 'desc',
            ];
        }
        return [
            'view' => 'desc',
            'sort' => 'desc',
            'create_at' => 'desc',
        ];
    }

    public function tabList()
    {
        $sql = new PohtoTypeModal();
        $list = $sql ->order('sort desc')
            ->order('create_at desc')->select();
        return result()->success($list);
    }
}